const http = require("http")
const fs = require("fs")
const mime = require('./mime.json')
const { resolve } = require('path')
const quotes = [
  '虽然我个子矮，但我发际线高啊！',
  '有些事情做不完，就留到明天做吧。运气好的话，明天死了就不用做了。',
  '善良没用，你得漂亮。',
  '好好活下去 每天都有新打击。',
  '活着的时候把自己搞得好看一点，这样你就不会死得太难看。',
  '世上无难事 只要肯放弃。',
  '加油，你是最胖的！'
];

const server = http.createServer((req, res) => {
  let url = req.url;
  let content = '';
  if (url.includes(".ico")) {
    res.end("")
  } else {
    // 动态/静态资源规则定制
    if (url.startsWith("/public")) {
      let filePath = '.' + url;
      // 获取.最后一次出现位置
      let lastPointIndex = filePath.lastIndexOf(".")
      // 截取后缀
      let suffix = filePath.substring(lastPointIndex)
      // 
      let mimeType = mime[suffix];
      res.writeHead(200, 'ok', {
        'content-type': mimeType + ';charset=utf-8'
      })
      content = fs.readFileSync(filePath)
      res.end(content)
    } else {
      if (url == '/getDate') {
        res.writeHead(200, 'ok', {
          'content-type': 'text/html; charset=utf-8'
        });
        res.end(new Date().toString())
      } else if (url == '/quote') {
        res.writeHead(200, 'ok', {
          'content-type': 'text/html; charset=utf-8'
        });
        res.end(quotes[Math.floor(Math.random()*quotes.length)])
      }
    }
  }
})
server.listen(8888, () => {
  console.log("启动成功")
})